package com.dy.yunying.biz.service.datacenter.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.dy.yunying.api.entity.*;
import com.dy.yunying.api.entity.hongbao.HbActivityRoleInfo;
import com.dy.yunying.api.entity.usergroup.UserGroup;
import com.dy.yunying.api.req.ParentGameReq;
import com.dy.yunying.api.req.usergroup.UserGroupDetailReq;
import com.dy.yunying.api.vo.usergroup.UserGroupDetailVo;
import com.dy.yunying.api.vo.usergroup.UserGroupExportVo;
import com.dy.yunying.biz.dao.ads.usergroup.UserGroupMapper;
import com.dy.yunying.biz.dao.datacenter.impl.UserGroupDetailDao;
import com.dy.yunying.biz.dao.manage.ChannelManageDOMapper;
import com.dy.yunying.biz.dao.manage.GameRoleMapper;
import com.dy.yunying.biz.dao.manage.WanGameChannelInfoMapper;
import com.dy.yunying.biz.dao.manage.WanUserMapper;
import com.dy.yunying.biz.service.datacenter.UserGroupDetailService;
import com.dy.yunying.biz.service.manage.GameRoleService;
import com.dy.yunying.biz.service.manage.GameService;
import com.dy.yunying.biz.service.manage.ParentGameService;
import com.dy.yunying.biz.service.manage.WanUserService;
import com.dy.yunying.biz.utils.DateUtils;
import com.pig4cloud.pig.api.entity.AdCampaignStatistic;
import com.pig4cloud.pig.common.core.util.R;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.apache.ibatis.jdbc.Null;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@Service
@RequiredArgsConstructor
public class UserGroupDetailServiceImpl implements UserGroupDetailService {

	private final UserGroupDetailDao userGroupDetailDao;

	private final ParentGameService parentGameService;

	private final GameService gameService;


	private final ChannelManageDOMapper channelManageDOMapper;

	private final WanGameChannelInfoMapper wanGameChannelInfoMapper;

	private final WanUserMapper wanUserMapper;

	private final UserGroupMapper userGroupMapper;

	private final GameRoleMapper gameRoleMapper;

	@Override
	public R list(UserGroupDetailReq req) {
		List<UserGroupDetailVo> list = userGroupDetailDao.list(req); // 查询数据
		dealData(list);
		return R.ok(list);
	}

	@Override
	public R count(UserGroupDetailReq req) {
		Long count = 0L;
		try {
			count = userGroupDetailDao.countDataTotal(req);
			//查询user_group群组用户表,查询当前用户数量
	/*		UserGroup userGroup = userGroupMapper.selectById(req.getGroupId());
			if(userGroup != null){
				count= userGroup.getUserNums();
			}*/
		} catch (Exception e) {
			log.error("countDataTotal:[{}]", e);
			return R.failed("用户群组总记录数查询失败");
		}
		return R.ok(count);
	}

	@Override
	public List<UserGroupExportVo> exportRecord(UserGroupDetailReq req) {
		req.setCurrent(1L);
		req.setSize(999999L);
		List<UserGroupDetailVo> list = userGroupDetailDao.list(req);
		// 处理数据
		List<UserGroupExportVo> userGroupExportVos = dealExportData(list);
		return userGroupExportVos;
	}


	//处理列表中的创建人，使用真实姓名
	public void dealData(List<UserGroupDetailVo> list) {
		try {
			if (CollectionUtils.isNotEmpty(list)) {
				// 获取父游戏列表
				Collection<Long> parentGameIds = list.stream().map(item -> {
					return Long.valueOf(String.valueOf(item.getAppMain()));
				}).collect(Collectors.toSet());
				List<ParentGameDO> parentGameList = parentGameService.getCacheablePGameList(new ParentGameReq().setIds(parentGameIds));
				Map<Long, String> parentGameMap = CollectionUtil.isEmpty(parentGameList) ? new HashMap<>() : parentGameList.stream().collect(Collectors.toMap(ParentGameDO::getId, ParentGameDO::getGname));

				// 获取群组分类-指定子游戏
				Set<Integer> gameIds = list.stream().map(UserGroupDetailVo::getAppCode).filter(Objects::nonNull).collect(Collectors.toSet());
				List<WanGameDO> gameList = CollectionUtils.isEmpty(gameIds) ? new ArrayList<>() : gameService.list(Wrappers.<WanGameDO>query().lambda().in(WanGameDO::getId, gameIds));
				//Map<用户ID,用户名称>
				Map<Long, String> gameMap = CollectionUtils.isEmpty(gameList) ? new HashMap<>() : gameList.stream().collect(Collectors.toMap(WanGameDO::getId, WanGameDO::getGname));

				// 填充主渠道名称
				final List<String> mainCodeList = list.stream().map(UserGroupDetailVo::getChlMain).distinct().filter(Objects::nonNull).collect(Collectors.toList());
				// 填充子渠道名称
				final List<String> subCodeList = list.stream().map(UserGroupDetailVo::getChlSub).distinct().filter(Objects::nonNull).collect(Collectors.toList());
				// 填充分包渠道名称
				final List<String> appCodeList = list.stream().map(UserGroupDetailVo::getChlApp).distinct().filter(Objects::nonNull).collect(Collectors.toList());

				List<ChannelManageDO> mainChl = CollectionUtils.isEmpty(mainCodeList) ? new ArrayList<>() :  channelManageDOMapper.selectList(Wrappers.<ChannelManageDO>lambdaQuery().select(ChannelManageDO::getChncode, ChannelManageDO::getChnname).in(ChannelManageDO::getChncode, mainCodeList).eq(ChannelManageDO::getPid, NumberUtils.INTEGER_ZERO));
				final Map<String, String> parentchlMap = CollectionUtils.isEmpty(mainChl) ? new HashMap<>() :  mainChl.stream().collect(Collectors.toMap(ChannelManageDO::getChncode, channel -> StringUtils.isBlank(channel.getChnname()) ?  channel.getChncode() : channel.getChnname(), (k1, k2) -> k1));


				List<ChannelManageDO> subChl = CollectionUtils.isEmpty(subCodeList) ? new ArrayList<>() :  channelManageDOMapper.selectList(Wrappers.<ChannelManageDO>lambdaQuery().select(ChannelManageDO::getChncode, ChannelManageDO::getChnname).in(ChannelManageDO::getChncode, subCodeList).ne(ChannelManageDO::getPid, NumberUtils.INTEGER_ZERO));
				final Map<String, String> subChlMap = CollectionUtils.isEmpty(subChl) ? new HashMap<>() :  subChl.stream().collect(Collectors.toMap(ChannelManageDO::getChncode, channel -> StringUtils.isBlank(channel.getChnname()) ?  channel.getChncode() : channel.getChnname(), (k1, k2) -> k1));

				//增加手机号的搜索
				Set<String> usernames = list.stream().map(UserGroupDetailVo::getUsername).filter(Objects::nonNull).collect(Collectors.toSet());
				List<WanUser> mobileList = CollectionUtils.isEmpty(usernames) ? new ArrayList<>() :  wanUserMapper.selectList(Wrappers.<WanUser>lambdaQuery().select(WanUser::getUsername, WanUser::getMobile).in(WanUser::getUsername, usernames));
				//处理特殊情况为空
				final Map<String, String> mobileMap = CollectionUtils.isEmpty(mobileList) ? new HashMap<>() :  mobileList.stream().collect(Collectors.toMap(WanUser::getUsername, user -> StringUtils.isBlank(user.getMobile()) ? "-" : user.getMobile(), (k1, k2) -> k1));


				//获得账号的注册时间
				//获得账号的列表
				List<WanUser> regTimeList = CollectionUtils.isEmpty(usernames) ? new ArrayList<>() : wanUserMapper.selectList(Wrappers.<WanUser>lambdaQuery().
						select(WanUser::getUsername, WanUser::getRegtime).in(WanUser::getUsername, usernames));

				Map<String, String> regTimeMap = CollectionUtil.isEmpty(regTimeList) ? new HashMap<>() : regTimeList.stream().
						collect(Collectors.toMap(WanUser::getUsername, user ->  user.getRegtime() == null ? "" : DateUtils.dateToString(user.getRegtime(),DateUtils.YYYY_MM_DD_HH_MM_SS), (k1, k2) -> k1));


				//获得角色的创角时间
				Set<String> roleIds = list.stream().map(UserGroupDetailVo::getRoleId).filter(Objects::nonNull).collect(Collectors.toSet());

				List<GameRole> gameRoleList = CollectionUtils.isEmpty(roleIds) ? new ArrayList<>() : gameRoleMapper.selectList(Wrappers.<GameRole>lambdaQuery().
						select(GameRole::getRoleId, GameRole::getCreateRoleTime).in(GameRole::getRoleId, roleIds));

				Map<String, String> createRoleTimeMap = CollectionUtil.isEmpty(gameRoleList) ? new HashMap<>() : gameRoleList.stream().
						collect(Collectors.toMap(GameRole::getRoleId,user ->  user.getCreateRoleTime() == null ? "" : DateUtils.dateToString(user.getCreateRoleTime(),DateUtils.YYYY_MM_DD_HH_MM_SS), (k1, k2) -> k1));

				list.forEach((item) -> {
					if (CollectionUtil.isNotEmpty(gameMap) && item.getAppCode() != null) {
						item.setGameName(gameMap.get(item.getAppCode().longValue()));
					}
					if (CollectionUtil.isNotEmpty(parentGameMap) && item.getAppMain() != null) {
						item.setParentGameName(parentGameMap.get(item.getAppMain().longValue()));
					}
					if (CollectionUtil.isNotEmpty(parentchlMap) && item.getChlMain() != null) {
						item.setParentchl(parentchlMap.get(item.getChlMain()));
					}
					if (CollectionUtil.isNotEmpty(subChlMap) && item.getChlSub() != null) {
						item.setChl(subChlMap.get(item.getChlSub()));
					}
					if (CollectionUtil.isNotEmpty(mobileMap) && StringUtils.isNotBlank(item.getUsername())) {
						item.setMobile(mobileMap.get(item.getUsername()));
					}

					if(CollectionUtil.isNotEmpty(regTimeMap) && StringUtils.isNotBlank(item.getUsername())){
						item.setAccountRegTime(regTimeMap.get(item.getUsername()));
					}

					if(CollectionUtil.isNotEmpty(createRoleTimeMap) && StringUtils.isNotBlank(item.getRoleId())){
						item.setRoleRegTime(createRoleTimeMap.get(item.getRoleId()));
					}

					String deviceBrand = StringUtils.isBlank(item.getDeviceBrand()) ? "" : item.getDeviceBrand();
					String deviceModel = StringUtils.isBlank(item.getDeviceModel()) ? "" : item.getDeviceModel();
					item.setDevice(deviceBrand + "-" + deviceModel);
					//地区
					String province = StringUtils.isBlank(item.getProvince()) ? "" : item.getProvince();
					String city = StringUtils.isBlank(item.getCity()) ? "" : item.getCity();
					item.setArea(province + "-" + city);
				});
			}
		} catch (Throwable t) {
			log.error("处理数据异常", t);
		}
	}

	//处理列表中的创建人，使用真实姓名
	public List<UserGroupExportVo> dealExportData(List<UserGroupDetailVo> list) {
		List<UserGroupExportVo> userGroupExportVos = new ArrayList<>();
		try {
			if (CollectionUtils.isNotEmpty(list)) {
				// 获取父游戏列表
				Collection<Long> parentGameIds = list.stream().map(item -> {
					return Long.valueOf(String.valueOf(item.getAppMain()));
				}).collect(Collectors.toSet());
				List<ParentGameDO> parentGameList = parentGameService.getCacheablePGameList(new ParentGameReq().setIds(parentGameIds));
				Map<Long, String> parentGameMap = CollectionUtil.isEmpty(parentGameList) ? new HashMap<>() : parentGameList.stream().collect(Collectors.toMap(ParentGameDO::getId, ParentGameDO::getGname));

				// 获取群组分类-指定子游戏
				Set<Integer> gameIds = list.stream().map(UserGroupDetailVo::getAppCode).filter(Objects::nonNull).collect(Collectors.toSet());
				List<WanGameDO> gameList = CollectionUtils.isEmpty(gameIds) ? new ArrayList<>() : gameService.list(Wrappers.<WanGameDO>query().lambda().in(WanGameDO::getId, gameIds));
				//Map<用户ID,用户名称>
				Map<Long, String> gameMap = CollectionUtils.isEmpty(gameList) ? new HashMap<>() : gameList.stream().collect(Collectors.toMap(WanGameDO::getId, WanGameDO::getGname));

				// 填充主渠道名称
				final List<String> mainCodeList = list.stream().map(UserGroupDetailVo::getChlMain).distinct().filter(Objects::nonNull).collect(Collectors.toList());
				// 填充子渠道名称
				final List<String> subCodeList = list.stream().map(UserGroupDetailVo::getChlSub).distinct().filter(Objects::nonNull).collect(Collectors.toList());
				// 填充分包渠道名称
				final List<String> appCodeList = list.stream().map(UserGroupDetailVo::getChlApp).distinct().filter(Objects::nonNull).collect(Collectors.toList());

				List<ChannelManageDO> mainChl = CollectionUtils.isEmpty(mainCodeList) ? new ArrayList<>() :  channelManageDOMapper.selectList(Wrappers.<ChannelManageDO>lambdaQuery().select(ChannelManageDO::getChncode, ChannelManageDO::getChnname).in(ChannelManageDO::getChncode, mainCodeList).eq(ChannelManageDO::getPid, NumberUtils.INTEGER_ZERO));
				final Map<String, String> parentchlMap = CollectionUtils.isEmpty(mainChl) ? new HashMap<>() :  mainChl.stream().collect(Collectors.toMap(ChannelManageDO::getChncode, channel -> StringUtils.isBlank(channel.getChnname()) ?  channel.getChncode() : channel.getChnname(), (k1, k2) -> k1));


				List<ChannelManageDO> subChl = CollectionUtils.isEmpty(subCodeList) ? new ArrayList<>() :  channelManageDOMapper.selectList(Wrappers.<ChannelManageDO>lambdaQuery().select(ChannelManageDO::getChncode, ChannelManageDO::getChnname).in(ChannelManageDO::getChncode, subCodeList).ne(ChannelManageDO::getPid, NumberUtils.INTEGER_ZERO));
				final Map<String, String> subChlMap = CollectionUtils.isEmpty(subChl) ? new HashMap<>() :  subChl.stream().collect(Collectors.toMap(ChannelManageDO::getChncode, channel -> StringUtils.isBlank(channel.getChnname()) ?  channel.getChncode() : channel.getChnname(), (k1, k2) -> k1));

				//增加手机号的搜索
				Set<String> usernames = list.stream().map(UserGroupDetailVo::getUsername).filter(Objects::nonNull).collect(Collectors.toSet());
				List<WanUser> mobileList = CollectionUtils.isEmpty(usernames) ? new ArrayList<>() :  wanUserMapper.selectList(Wrappers.<WanUser>lambdaQuery().select(WanUser::getUsername, WanUser::getMobile).in(WanUser::getUsername, usernames));
				//处理特殊情况为空
				final Map<String, String> mobileMap = CollectionUtils.isEmpty(mobileList) ? new HashMap<>() :  mobileList.stream().collect(Collectors.toMap(WanUser::getUsername, user -> StringUtils.isBlank(user.getMobile()) ? "-" : user.getMobile(), (k1, k2) -> k1));


				//获得账号的注册时间
				//获得账号的列表
				List<WanUser> regTimeList = CollectionUtils.isEmpty(usernames) ? new ArrayList<>() : wanUserMapper.selectList(Wrappers.<WanUser>lambdaQuery().
						select(WanUser::getUsername, WanUser::getRegtime).in(WanUser::getUsername, usernames));

				Map<String, String> regTimeMap = CollectionUtil.isEmpty(regTimeList) ? new HashMap<>() : regTimeList.stream().
						collect(Collectors.toMap(WanUser::getUsername, user ->  user.getRegtime() == null ? "" : DateUtils.dateToString(user.getRegtime(),DateUtils.YYYY_MM_DD_HH_MM_SS), (k1, k2) -> k1));


				//获得角色的创角时间
				Set<String> roleIds = list.stream().map(UserGroupDetailVo::getRoleId).filter(Objects::nonNull).collect(Collectors.toSet());

				List<GameRole> gameRoleList = CollectionUtils.isEmpty(roleIds) ? new ArrayList<>() : gameRoleMapper.selectList(Wrappers.<GameRole>lambdaQuery().
						select(GameRole::getRoleId, GameRole::getCreateRoleTime).in(GameRole::getRoleId, roleIds));

				Map<String, String> createRoleTimeMap = CollectionUtil.isEmpty(gameRoleList) ? new HashMap<>() : gameRoleList.stream().
						collect(Collectors.toMap(GameRole::getRoleId,user ->  user.getCreateRoleTime() == null ? "" : DateUtils.dateToString(user.getCreateRoleTime(),DateUtils.YYYY_MM_DD_HH_MM_SS), (k1, k2) -> k1));

				list.forEach((item) -> {
					if (CollectionUtil.isNotEmpty(gameMap) && item.getAppCode() != null) {
						item.setGameName(gameMap.get(item.getAppCode().longValue()));
					}
					if (CollectionUtil.isNotEmpty(parentGameMap) && item.getAppMain() != null) {
						item.setParentGameName(parentGameMap.get(item.getAppMain().longValue()));
					}
					if (CollectionUtil.isNotEmpty(parentchlMap) && item.getChlMain() != null) {
						item.setParentchl(parentchlMap.get(item.getChlMain()));
					}
					if (CollectionUtil.isNotEmpty(subChlMap) && item.getChlSub() != null) {
						item.setChl(subChlMap.get(item.getChlSub()));
					}
					if (CollectionUtil.isNotEmpty(mobileMap) && StringUtils.isNotBlank(item.getUsername())) {
						item.setMobile(mobileMap.get(item.getUsername()));
					}

					if(CollectionUtil.isNotEmpty(regTimeMap) && StringUtils.isNotBlank(item.getUsername())){
						item.setAccountRegTime(regTimeMap.get(item.getUsername()));
					}

					if(CollectionUtil.isNotEmpty(createRoleTimeMap) && StringUtils.isNotBlank(item.getRoleId())){
						item.setRoleRegTime(createRoleTimeMap.get(item.getRoleId()));
					}

					String deviceBrand = StringUtils.isBlank(item.getDeviceBrand()) ? "" : item.getDeviceBrand();
					String deviceModel = StringUtils.isBlank(item.getDeviceModel()) ? "" : item.getDeviceModel();
					item.setDevice(deviceBrand + "-" + deviceModel);
					//地区
					String province = StringUtils.isBlank(item.getProvince()) ? "" : item.getProvince();
					String city = StringUtils.isBlank(item.getCity()) ? "" : item.getCity();
					item.setArea(province + "-" + city);

					UserGroupExportVo userGroupExportVo = new UserGroupExportVo();

					BeanUtils.copyProperties(item, userGroupExportVo);
					userGroupExportVos.add(userGroupExportVo);
				});
			}
		} catch (Throwable t) {
			log.error("处理数据异常", t);
		}
		return userGroupExportVos;
	}

}
